package com.myfoon.servlet.pub;

import com.myfoon.model.entity.Photo;
import com.myfoon.model.entity.User;
import com.myfoon.model.entity.Video;
import com.myfoon.servlet.listener.UploadProgressListener;

import java.io.File;
import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.json.JSONObject;

public class UploadImage extends HttpServlet {
    private final static String directory = "/var/www/html/u";      // Uploads Real Directory
    private final static String webDir = "/u";                      // Web Directory    
    private final static String pDirectory = "photos"; // Photos Directory    
    private final static String tmpDirectory = "tmp"; // Photos Directory    
    
    private final static String imagesDirectory = "images";
    private final static String videosDirectory = "videos";
    
    public UploadImage() {
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
                                                                          IOException {               
        User user = (User)httpServletRequest.getSession(true).getAttribute("user");      
        List<Photo> photoList = null;        
        
        if (httpServletRequest.getSession(true).getAttribute("attachedImages") != null) {            
            photoList = (List<Photo>)httpServletRequest.getSession(true).getAttribute("attachedImages");
        }
        else {
            photoList = new ArrayList<Photo>();
        }
        
        httpServletResponse.setContentType("text/plain");                
                
        String userDir = directory + "/" + pDirectory + "/" + user.getId().toString() + "/";         
        String userTmp = directory + "/" + tmpDirectory + "/" + user.getId().toString() + "/";
        String fileName = String.valueOf(System.currentTimeMillis());        
                        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
                        
        new File(userDir).mkdirs();        
        new File(userTmp).mkdirs();
        factory.setRepository(new File(userTmp));
        
        ServletFileUpload upload = new ServletFileUpload(factory);                
        upload.setSizeMax(5000000);
                            
        try {
            List fileItems = upload.parseRequest(httpServletRequest);
            Iterator iter = fileItems.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem)iter.next();

                if (item.isFormField()) {

                } else {                                                                
                    System.out.println("Content Type: " + item.getContentType());
                    System.out.println("Name: " + item.getName());
                    System.out.println("Size: " + item.getSize());
                    System.out.println("Field Name: " + item.getFieldName());                    
                    File file = new File(userDir, fileName);                                          
                    item.write(file);  
                    
                    
                    JSONObject object = new JSONObject();
                    object.put("f_id", fileName);
                    object.put("f_type", "image");                    
                    object.put("f_name", item.getName());                    
                    object.put("f_url", webDir + "/" + pDirectory + "/" + user.getId().toString() + "/" + fileName);
                    
                    PrintWriter writer = httpServletResponse.getWriter();    
                    writer.println(object.toString());
                    
                    Photo photo = new Photo();
                    photo.setTempId(fileName);
                    photo.setOwner(user);
                    photo.setSrc(webDir + "/" + pDirectory + "/" + user.getId().toString() + "/" + fileName);
                    photo.setSrcsmall(webDir + "/" + pDirectory + "/" + user.getId().toString() + "/" + fileName);                
                    
                    photoList.add(photo);        
                    httpServletRequest.getSession(true).setAttribute("attachedImages", photoList);                                        
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }   
}
